/*
 * Middleware
 * Copyright (C) 2010/11
 * Riccardo Pulvirenti, Giuseppe Ravidà, Andrea Tino
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANDABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses
 */

/*!
 * File: utils.cpp
 */

#include <iostream>
#include <fstream>
#include <string>
#include <exception>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/lexical_cast.hpp>

#include "utils.hpp"

//-----------------------------------------------------------------------------
// Function implementations
namespace middleware {
namespace utils {
std::string GetRandomIntegralNumberStr(int min, int max) {
	int value = GetRandomIntegralNumberInt(min, max);
	return boost::lexical_cast<std::string>(value);
}
int GetRandomIntegralNumberInt(int min, int max) {
	/* Static is essential in order to let the randomstream proceed */
	static boost::mt19937 gen(static_cast<unsigned int>(std::time(0)));
	boost::uniform_int<> dist(min, max);
	boost::variate_generator< boost::mt19937&, boost::uniform_int<> >
		var(gen, dist);
	int value = (int)var();
	return value;
}
int GetRandomIntegralNumber(unsigned int max) {
    std::ifstream rand("/dev/urandom");
    char tmp[sizeof(int)];
    rand.read(tmp,sizeof(int));
    rand.close();
    int* number = reinterpret_cast<int*>(tmp);
    if ((*number) < 0) *number = (-1)*(*number);
    *number = (*number) % (max + 1);
    return (*number);
}
}
}
